import { z } from 'zod';
import { isValid, parse } from 'date-fns';

export const expenseSchema = z.object({
  siteId: z.string().min(1, '工地ID不能为空'),
  type: z.enum(['material', 'labor', 'equipment', 'other'], {
    errorMap: () => ({ message: '无效的支出类型' }),
  }),
  amount: z.number().positive('金额必须大于0'),
  paymentDate: z.string().refine(
    (date) => {
      try {
        return isValid(parse(date, 'yyyy-MM-dd', new Date()));
      } catch {
        return false;
      }
    },
    {
      message: '日期格式必须为 YYYY-MM-DD',
    }
  ),
  vendor: z.string().optional(),
  description: z.string().optional(),
});

export type ExpenseInput = z.infer<typeof expenseSchema>;

export async function validateExpenseInput(data: unknown) {
  try {
    const validatedData = await expenseSchema.parseAsync(data);
    return {
      success: true as const,
      data: validatedData,
    };
  } catch (error) {
    if (error instanceof z.ZodError) {
      const firstError = error.errors[0];
      return {
        success: false as const,
        error: {
          message: firstError.message,
          path: firstError.path,
        },
      };
    }
    return {
      success: false as const,
      error: {
        message: '数据验证失败',
        path: [],
      },
    };
  }
} 